<template>
  <el-select
    v-model="selectedValue"
    :placeholder="placeholder"
    :clearable="clearable"
    :loading="loading"
    :disabled="disabled"
    class="vt-select"
    @change="handleChange"
    @clear="handleClear"
  >
    <el-option
      v-for="item in options"
      :key="item.id || item.value"
      :label="showNameOnly ? getNameFromValue(item.value) : item.label"
      :value="item.value"
    />
  </el-select>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useVtOptionsStore } from "@/store/modules/vt-options.store.js";

defineOptions({
  name: "VtSelect",
  inheritAttrs: false,
});

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: "",
  },
  type: {
    type: String,
    required: true,
    validator: (value) =>
      ["bagType", "compositeType", "material", "size", "surfaceFee", "accessory"].includes(value),
  },
  filterType: {
    type: [String, Number],
    default: undefined,
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  clearable: {
    type: Boolean,
    default: true,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  showNameOnly: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue", "change", "clear"]);

const vtOptionsStore = useVtOptionsStore();
const loading = ref(false);
const options = ref([]);

const selectedValue = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

// 获取选项数据的方法映射
const storeMethodMap = {
  bagType: vtOptionsStore.getBagTypeOptions,
  compositeType: vtOptionsStore.getCompositeTypeOptions,
  material: vtOptionsStore.getMaterialOptions,
  size: vtOptionsStore.getSizeOptions,
  surfaceFee: vtOptionsStore.getSurfaceFeeOptions,
  accessory: vtOptionsStore.getAccessoryOptions,
};

// 加载选项数据
async function loadOptions() {
  if (!storeMethodMap[props.type]) {
    console.warn(`VtSelect: 不支持的类型 "${props.type}"`);
    return;
  }

  loading.value = true;
  try {
    let rawOptions;
    // 如果是bagType类型且有filterType，传递过滤参数
    if (props.type === "bagType" && props.filterType !== undefined) {
      rawOptions = await storeMethodMap[props.type](props.filterType);
    } else {
      rawOptions = await storeMethodMap[props.type]();
    }

    // 如果是材质类型且启用了showNameOnly，修改value为只包含名称
    if (props.type === "material" && props.showNameOnly) {
      options.value = rawOptions.map((item) => ({
        ...item,
        value: item.value.split("-")[0], // 只取材质名称部分
      }));
    } else {
      options.value = rawOptions;
    }
  } catch (error) {
    console.error(`VtSelect: 加载${props.type}选项失败`, error);
    options.value = [];
  } finally {
    loading.value = false;
  }
}

function handleChange(value) {
  const selectedOption = options.value.find((item) => item.value === value);
  emit("change", value, selectedOption);
}

function handleClear() {
  emit("clear");
}

// 从value中提取纯净的名称
function getNameFromValue(value) {
  if (!value) return "";

  // 对于不同类型的数据，提取名称的方式不同
  switch (props.type) {
    case "material":
      // 如果启用了showNameOnly，value已经是纯名称了
      if (props.showNameOnly) {
        return value;
      }
      // 否则从格式"材质名-厚度"中提取材质名
      return value.split("-")[0];
    case "size":
      // 尺寸格式：长×宽+高，保持原样
      return value;
    default:
      // 其他类型直接返回value作为名称
      return value;
  }
}

onMounted(() => {
  loadOptions();
});

// 监听type和filterType变化，重新加载数据
watch(
  () => [props.type, props.filterType],
  () => {
    loadOptions();
  }
);
</script>
<style scoped lang="scss">
.vt-select {
  width: 100%;
  min-width: 150px;
}
</style>
